package com.fm.service;

import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.Socket;
import java.util.Properties;
import java.util.Set;


@Slf4j
public class service_download {

    /**
     * 下载
     *
     * @param socket
     */
    public static void download(Socket socket) {
        try {
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            int i = dataInputStream.readInt();

            //加载映射
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/main/resources/config.properties"));

            //获取全部值
            Set<String> keys = properties.stringPropertyNames();
            int n = 1;
            String value;
            FileInputStream fileInputStream = null;
            for (String key : keys) {
                if (key.startsWith("uploadFileName.") && i == n++) {
                    fileInputStream = new FileInputStream("src/main/resources/upLoad/" + key.replace("uploadFileName.", ""));
                    value = properties.getProperty(key);
                    DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    //传输文件名
                    dataOutputStream.writeInt(value.getBytes().length);
                    socket.getOutputStream().write(value.toString().getBytes());
                }
            }

            //传输下载文件
            byte[] bytes = new byte[1024];
            int len;
            while ((len = (fileInputStream.read(bytes))) != -1) {
                socket.getOutputStream().write(bytes, 0, len);
            }

            //关闭
            socket.getOutputStream().close();
            socket.close();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
